﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Configuration;
using System.IO;
using System.Text;
using System.Data;
using System.Web;
using System.Web.Mvc;
using Lead2012.Business;
using Lead2012.Models;
using Lead2012.ViewModels;
using Lead2012.Repository;

namespace Lead2012.Controllers
{
    public class LeadImportController : BaseController
    {
        // Create an instance of repository
        LeadImportManagementRepository repository = new LeadImportManagementRepository();

        [Authorize(Roles = "Administrator,Registered")]
        public ActionResult Index()
        {
            LeadImportViewModel model = new LeadImportViewModel();
            SetupCommon(model, string.Empty, "Name");

            return View(model);
        }
        
        // 01. Download a sample file
        [Authorize(Roles = "Administrator,Registered")]
        [HttpGet]
        public ActionResult GetSampleFile()
        {
            int numOfColumn = Convert.ToInt32(ConfigurationManager.AppSettings["NumberOfColumns"]);
            if (numOfColumn < 1) numOfColumn = 20;

            List<FieldInfo> fieldList = repository.GetAllFieldSample();
            MemoryStream output = new MemoryStream();
            StreamWriter writer = new StreamWriter(output, Encoding.UTF8);

            int count = fieldList.Count;
            int index = 0;
            foreach (FieldInfo fi in fieldList)
            {
                if (index < numOfColumn)
                {
                    if ((index > 0) && (index < count))
                    {
                        writer.Write(",");
                    }
                    writer.Write("\"" + fi.Title + "\"");
                    index++;
                }
                else
                {
                    break;
                }
            }
            writer.Flush();
            output.Position = 0;

            return File(output, "text/csv", "sample.csv");
        }

        // 02. Upload a file with formats: .xls, .xlsx, .csv
        [HttpPost]
        public ActionResult Upload(string token, HttpPostedFileBase fileData)
        {
            LeadImportViewModel model = new LeadImportViewModel();
            HttpPostedFileBase file = Request.Files[0];

            if (file != null && file.ContentLength > 0)
            {
                // extract only the fielname
                // Save a file uploaded on /Upload/ folder
                string fileName = Path.GetFileName(file.FileName);
                string fileExt = fileName.Substring(fileName.LastIndexOf("."));
                string storedFilePath = Path.Combine(Server.MapPath(ConfigurationManager.AppSettings["UploadFile"]), string.Format("{0}-{1}", Guid.NewGuid(), fileName));
                file.SaveAs(storedFilePath);

                // Assign values to model
                model.StoreFilePath = storedFilePath;
            }
            else
            {
                model.IsError = true;
                model.ErrorMessage = "Tài liệu tải lên là rỗng";
            }

            return Json(model);
        }

        // 03. Parse data and mapping sample.csv with system columns
        [HttpPost]
        public ActionResult GetMapping(string file)
        {
            LeadImportViewModel model = new LeadImportViewModel();

            model = repository.GetMappingModel(file);

            return Json(model, JsonRequestBehavior.AllowGet);
        }

        // 04. Retrieve all data mapped and return to view
        [HttpPost]
        public ActionResult GetAllDataMapping(string file, List<ColumnModel> MappingSettings)
        {
            LeadImportViewModel model = new LeadImportViewModel();

            // First: Get all mapped on view
            // Calculate data return to view with ordered
            model = repository.GetMappedWithDataModel(file, MappingSettings);

            // Second: Set data to model to return view
            JsonResult results = Json(model, JsonRequestBehavior.AllowGet);

            return results;
        }

        // 05. Save data to database and return status of process
        [HttpPost]
        public ActionResult SendDataToServ(List<ColumnHeaderModel> headColumns, RowModel errorRow)
        {
            // Save data to db
            // Call a method to save data
            repository.AddNewLead(headColumns, errorRow);

            return Json(string.Empty, JsonRequestBehavior.AllowGet);
        }
    }
}
